--UIEquipsProps
--create by daisl
--选取道具子界面

-- 每行最大道具数量
local MAX_PROPS = 5;

-- 无道具时，显示的空框数量
local EMPTY_NUM = 25;

UIEquipsProps = class("UIEquipsProps",function()
	return cc.Layer:create();
end);

function UIEquipsProps.create(propTable, parent)
    return UIEquipsProps.new(propTable,  parent);
end

-- 函数内部声明
local resize;
local initItem;
local descEquip;
local redrawItemStar;

function UIEquipsProps:ctor(propTable, parent)
    self:setName("UIEquipsProps");

    --需要显示在英雄子菜单前面
    self:setLocalZOrder(UIMgr.HERO_SUBMENU_ZORDER+1);

    local node = cc.CSLoader:createNode("layout/equips/equipProps.csb")
    self:addChild(node);
    self.node = node;

    local iconNode = cc.CSLoader:createNode("layout/equips/propIcon.csb")
    self.widget = replaceNodeWithWidget(iconNode);
    self.widget:retain();

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(event)
        if event == "exit" then
            self.widget:release();
        end
    end);

    -- 选中的框
    self.frameSelected = parent;

    -- 标记被选中的
    self.equipSelected = nil;

    -- 装备数据
    self.propTable = propTable;

    resize(node);

    -- 初始化道具列表
    self:initProps();

    -- 按钮处理
    self:initButtons();
end

resize = function (node)
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg1");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    local text = findChildByName(node, "CT/top_text");
    TextStyleM.setOutlineStyle(text);
end

-- 初始化道具列表
function UIEquipsProps:initProps()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local scrollView = findChildByName(self.node,"CT/scrollview");

    local amount = 0;
    local classId;
    self.classId = {};
    self.propNum = {};
    for k,var in pairs(self.propTable) do
        amount = var["amount"];
        classId = var["classId"];
        table.insert(self.propNum,amount);
        table.insert(self.classId,classId);
    end

    -- 道具数量
    local propNum = EMPTY_NUM;
    if #self.propNum >  propNum then
        propNum = #self.propNum;
    end

    -- 道具数量文本显示
    self:initTopText(#table.keys(self.classId), propNum);
    -- 间距
    local gap = 0;

    local scrollWidth = scrollView:getContentSize().width;
    -- 图标宽度
    local iconWidth = (scrollWidth - (MAX_PROPS + 1) * gap) / MAX_PROPS;

    -- 先计算总高度
    local totalHeight = math.max((math.ceil(propNum / MAX_PROPS)) * (iconWidth + gap),
        scrollView:getInnerContainerSize().height);

    scrollView:setInnerContainerSize(cc.size(scrollView:getInnerContainerSize().width, totalHeight));

    local leftMargin = 15;
    -- 排列图标
    self.equipIcons = {};
    for i=1,propNum do
        local child = self.widget:clone();
        local x = (((i-1) % MAX_PROPS))*iconWidth + (iconWidth/2) + gap;
        local y = totalHeight - math.floor((i-1) / MAX_PROPS) * (iconWidth+gap) - (iconWidth/2+gap);
        child:setPositionX(x);
        child:setPositionY(y);

        -- 设置装备图标和数量
        initItem(child,self.classId[i], self.propNum[i], i);

        local icon = child:getChildByName("icon");
        local function onIconClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                self:onPropSelected(sender:getTag(), self.classId[i]);
            end
        end
        icon:addTouchEventListener(onIconClick);

        scrollView:addChild(child);

        table.insert(self.equipIcons, child);
    end
    scrollView:scrollToTop(0.1, true);
    UIIndicator.attach(scrollView);
end

function UIEquipsProps:initTopText (currenNum, allNum)

    if  not currenNum then
        currenNum = 0;
    end
    local firstText = findChildByName(self.node,"CT/first_text");
    local thirdText = findChildByName(self.node,"CT/third_text");

    firstText:setString(currenNum);
    thirdText:setString(allNum);

end
-- 高亮选中的装备
function UIEquipsProps:onPropSelected(index, classId)

    local text = findChildByName(self.node, "CT/bottom_text");
    for i = 1, #self.equipIcons do
        local iconLight = self.equipIcons[i]:getChildByName("farme_light");
        if i == index then
            self.idSelected = classId;
            iconLight:setVisible(true);

            --属性描述
            descEquip(text, classId);
        else
            iconLight:setVisible(false);
        end
    end
    TextStyleM.setOutlineStyle(self.equipBtn);
    self.equipBtn:setTouchEnabled(true);
    self.equipBtn:setBright(true);
end

-- 武器属性描述
descEquip = function (text, classId)

    local props = EquipM.query(classId, "prop");

    -- 遍历属性的描述
    local linkDesc = "";
    for _, prop in pairs(props) do
        local desc = PropM.getPropDesc(prop).."。";
         linkDesc = desc..linkDesc;
    end

    local name = ItemM.query(classId, "name");
    applyString(text, name..":"..linkDesc);
end

-- 按钮处理
function UIEquipsProps:initButtons()
    -- 窗口关闭处理
    local base = findChildByName(self.node, "CT/base");
    local btnBack = base:getChildByName("close");

    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            UIMgr.getCurrentScene():removeForm(self);
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- ”装备“按钮处理
    local equipBtn = findChildByName(self.node,"CT/equip_btn");
    equipBtn:setTouchEnabled(false);
    equipBtn:setBright(false);
    self.equipBtn = equipBtn;

    local function onEquipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self.frameSelected:setEquips(self.idSelected);
            UIMgr.getCurrentScene():removeForm(self);

        end
    end
    equipBtn:addTouchEventListener(onEquipClick);

end

-- 初始化装备图标
initItem = function (child, classId, num, i)
    if classId == nil then
        return;
    end

    local icon = child:getChildByName("icon");
    icon:setTag(i);
    icon:loadTexture(getItemIconPath(ItemM.query(classId, "icon")));
    icon:setVisible(true);

    local text = child:getChildByName("text");
    text:setProperty("./1234567890", "images/ui/common/shuzi3.png", 12, 23, ".")
    text:setString("/"..num);

    local rarity = ItemM.query(classId, "rarity");
    redrawItemStar(child, rarity);
end

-- 显示物品星级（稀有度）
function redrawItemStar(starParent, rarity)
    -- 显示物品星级
    for i = 1, MAX_ITEM_RARITY do
        local star = starParent:getChildByName("star" .. i);
        if type(rarity) ~= "number" then
            star:setVisible(false);
        elseif i <= rarity then
            star:setVisible(true);
        else
            star:setVisible(false);
        end
    end
end

